package com.sbtr.validate;

import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 验证字符串非空白 <br>
 * 执行器
 * @author qiujun
 * @date 2019-11-05
 */
public class LengthValidator implements ConstraintValidator<Length, String> {

    private boolean canEmpty;
    private boolean trim;
    private int min;
    private int max;
    private String msg;

    private static final String NOT_BLANK_MSG = "不能为空";

    /*
     * （非 Javadoc）
     *
     * @see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
     */
    @Override
    public void initialize(Length l) {
        this.canEmpty = l.canEmpty();
        this.trim = l.trim();
        this.min = l.min();
        this.max = l.max();
        this.msg = l.message();
        // 大小互换
        if (min > max) {
            this.max = l.min();
            this.min = l.max();
        }
    }

    /*
     * （非 Javadoc）
     *
     * @see javax.validation.ConstraintValidator#isValid(java.lang.Object, javax.validation.ConstraintValidatorContext)
     */
    public boolean isValid(String string, ConstraintValidatorContext constraintValidatorContext) {
        constraintValidatorContext.disableDefaultConstraintViolation();// 禁用默认的message信息

        // trim
        String str = (trim ? StringUtils.trim(string) : string);
        // 不允许为空，但是却为null
        if (null == str && !(canEmpty)) {
            constraintValidatorContext.buildConstraintViolationWithTemplate(NOT_BLANK_MSG).addConstraintViolation(); // 重新添加错误提示信息
            return false;
        }
        // 允许empty
        if (StringUtils.isEmpty(str) && canEmpty)
            return true;
        // check
        int length = str.length();
        if (min <= length && length <= max)
            return true;
        constraintValidatorContext.buildConstraintViolationWithTemplate(msg).addConstraintViolation(); // 重新添加错误提示信息
        return false;
    }

}

